package com.cqupt.service.impl;
import com.alibaba.fastjson.*;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.cqupt.service.BasicalItemService;
import com.cqupt.utils.APIUtils;
import com.cqupt.utils.DateUtils;
import com.cqupt.utils.PageUtils;
import com.cqupt.utils.TextUtils;
//import org.apache.commons.collections4.multimap.HashSetValuedHashMap;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;

@Service
@Transactional
public class BasicalItemServiceImpl implements BasicalItemService {
    /**
     * 通过指定的名称比如CPU utilization，来查询到基本监控设备信息，然后返回给前台展示
     * @param hostId 主机id
     * @param itemName 监控项
     * @param type 类型
     * @return
     */
    @Override
    public List<Map<String, Object>> getUtilizationByName(String hostId,String itemName,String type) {
        String token= APIUtils.getToken();
        //需要返回主机中的itemId和name属性
        String[] items = new String[] {"itemid","name"};
        // 已弃用 (监控项读写)
        String[] key_list = new String[] {"vfs.dev.read[,,]","vfs.dev.write[,,]"};
        Map<String, Object> paramsMap = new HashMap<String, Object>(){{
            put("jsonrpc", "2.0");
            put("method", "item.get");
            put("id", 1);
            put("auth", token);
            if (type.equals("Linux")){
                put("params", new HashMap<String, Object>(){{
                    put("searchByAny",true);
                    put("output", items);
                    put("hostids",hostId);
                    put("search", new HashMap<String, Object>(){{
                        if (itemName.equals("Disk write rate")){
                            put("key_", "vfs.dev.write[,,]");
                        }else if (itemName.equals("Disk read rate")){
                            put("key_", "vfs.dev.read[,,]");
                        }
                    }});
                }});
            }else{
                put("params", new HashMap<String, Object>(){{
                    put("searchByAny",true);
                    put("output", items);
                    put("hostids",hostId);
                    put("search", new HashMap<String, Object>(){{
                        put("name", itemName);
                    }});
                }});
            }
        }};
        // 封装数据
        Map<String, Object> responseMap = APIUtils.sendRequest(JSON.toJSONString(paramsMap, SerializerFeature.WriteMapNullValue));
       List<Map<String, Object>> resultTempList = (List<Map<String, Object>>)responseMap.get("result");
       if(resultTempList.size()==0)
       {
           // 打印结果
           System.out.println(itemName+":该监控项不存在");
       }
       else{
           //监控项中要返回的历史对象类型
           int historyType=0;
           if("net.if.collisions".equals(itemName) || "Number of processes".equals(itemName)||"Interface eth0: Bits sent".equals(itemName))
           {
               historyType=3;
           }
           //得到监控项的id
           String itemid=resultTempList.get(0).get("itemid").toString();
           int finalHistoryType = historyType;
           Map<String, Object> paramsMapItemValue = new HashMap<String, Object>(){{
               put("jsonrpc", "2.0");
               put("method", "history.get");
               put("id", 1);
               put("auth", token);
               //put("itemids",itemIds);
               put("params", new HashMap<String, Object>(){{
                   put("searchByAny",true);
                   put("output", "extend");
                   put("history", finalHistoryType);
                   put("itemids", itemid);
                   // 按时间排序
                   put("sortfield", "clock");
                   // 逆序
                   put("sortorder", "DESC");
                   put("limit",20);
               }});
           }};
           // 封装数据
           Map<String, Object> responseMapItemValue = APIUtils.sendRequest(JSON.toJSONString(paramsMapItemValue, SerializerFeature.WriteMapNullValue));
           List<Map<String, Object>> resultList = (List<Map<String, Object>>)responseMapItemValue.get("result");
           //格式化时间，yyyy：mm：ss
           for (int i = 0; i < resultList.size(); i++) {
               DateUtils.formatListDate(resultList.get(i),"clock");
           }
           return resultList;
       }
       return resultTempList;
    }

    /**
     * 通过给定数据返回实时的值
     * @param hostId 主机id
     * @return
     */
    @Override
    public List<Map<String, Object>> getRealDataByName(String hostId) {
        String token= APIUtils.getToken();
        //需要返回主机中的itemId和name属性
        String[] items = new String[] {"itemid","name","lastvalue","type"};
        //请求的数据
        String [] data =new String[]{"Load average (1m avg)","CPU utilization","net.if.collisions","Number of processes","Interrupts per second","Available memory in %","Total memory","vda: Disk utilization","System boot time","Operating system","Total swap space","Space utilization","Total space","Used space","System description","Uptime","Memory utilization"};
        Map<String, Object> paramsMap = new HashMap<String, Object>(){{
            put("jsonrpc", "2.0");
            put("method", "item.get");
            put("id", 1);
            put("auth", token);
            put("params", new HashMap<String, Object>(){{
                // 搜索参数
                put("searchByAny",true);
                put("output", items);
                put("hostids",hostId);
                put("search", new HashMap<String, Object>(){{
                    put("name", data);
                }});
            }});
        }};
        // 封装数据
        Map<String, Object> responseMap = APIUtils.sendRequest(JSON.toJSONString(paramsMap, SerializerFeature.WriteMapNullValue));
        String[] items1 = new String[] {"type"};
        Map<String, Object> par = new HashMap<String, Object>(){{
            put("jsonrpc", "2.0");
            put("method", "hostinterface.get");
            put("id", 1);
            put("auth", token);
            put("params", new HashMap<String, Object>(){{
                put("output", items1);
                put("hostids",hostId);
            }});
        }};
        // 封装数据
        Map<String, Object> responseMap1 = APIUtils.sendRequest(JSON.toJSONString(par, SerializerFeature.WriteMapNullValue));
        //jsonArray对象进行值的获取
        JSONArray jsonArray=(JSONArray)responseMap1.get("result");
        String type= jsonArray.getJSONObject(0).getString("type");
        jsonArray=(JSONArray)responseMap.get("result");
//        System.out.println(jsonArray);
        Map<String,Object> map = new HashMap<>();
        map.put("deviceType",type);
        List<Map<String, Object>> resultList = (List<Map<String, Object>>)responseMap.get("result");
        // 初始化总大小
        long totalSpace = 0L;
        long usedSpace = 0l;
        String systemOp = "";
        for (Map<String, Object> stringObjectMap : resultList) {
             String s = (String) stringObjectMap.get("name");
             if(s.contains("Total space"))
             {
                  totalSpace+=Long.parseLong((String) stringObjectMap.get("lastvalue"));
             }
             else if(s.contains("Used space"))
             {
                 usedSpace+=Long.parseLong((String) stringObjectMap.get("lastvalue"));
             }
            if("System boot time".equals(stringObjectMap.get("name")))
            {
                DateUtils.formatListDate(stringObjectMap,"lastvalue");
            }
            if("Uptime".equals(stringObjectMap.get("name")))
            {
                Date date = new Date();
                long start = date.getTime();
                long end = Long.valueOf(stringObjectMap.get("lastvalue")+"000");
                long finalTime = start-end;
                SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String uptime = sf.format(finalTime);
                stringObjectMap.put("lastvalue",uptime);
//                DateUtils.formatRunDate(stringObjectMap,"lastvalue");
            }
            if("System description".equals(stringObjectMap.get("name")))
            {
                systemOp =  (String) stringObjectMap.get("lastvalue");
            }
        }
        map.put("Systemdescription",systemOp);
        map.put("totalSpace",totalSpace);
        map.put("usedSpace",usedSpace);
        jsonArray.add(0,map);
//        System.out.println(resultList);
        return resultList;
    }

    /**
     * 给定ItemID和HostID返回实时数据
     * @param hostId 主机id
     * @param itemId 监控项名字
     * @return
     */
    @Override
    public List<Map<String, Object>> getDataByItemID(String hostId, String itemId) {
        String token= APIUtils.getToken();
        //需要返回主机中的itemId和name属性
        //请求的数据
        Map<String, Object> paramsMap = new HashMap<String, Object>(){{
            put("jsonrpc", "2.0");
            put("id","1");
            put("method", "item.get");
            put("auth", token);
            put("params", new HashMap<String, Object>(){{
                put("output","extend");
                put("itemids",itemId);
            }});
        }};
        // 封装数据
        Map<String, Object> responseMap = APIUtils.sendRequest(JSON.toJSONString(paramsMap, SerializerFeature.WriteMapNullValue));
        List<Map> result = (List<Map>) responseMap.get("result");
        // 获取监控项名称
        String itemName = result.get(0).get("name").toString();
        return this.getUtilizationByName(hostId, itemName,null);
    }

    /**
     * 通过给定的主机id获得所有的监控项
     * @param hostId 主机id
     * @param curPage  当前页
     * @param pageSize 页面大小
     * @param checkList 在线主机
     * @return
     */
    @Override
    public List<Map<String, Object>> getAllItems(String hostId,String curPage, String pageSize,String[]checkList) {
        // 转化为map
        Map<String, String> initHostItem = TextUtils.getDataToMap();
        String token = APIUtils.getToken();
        List<String> itemList = new ArrayList<>();
        itemList.add("itemid");
        itemList.add("name");
        itemList.add("lastvalue");
        itemList.add("lastclock");
        Map<String, Object> paramsMap = new HashMap<String, Object>(){{
            put("auth",token);
            put("jsonrpc", "2.0");
            put("method", "item.get");
            put("id", 1);
            put("params",new HashMap<String,Object>(){{
                put("output",itemList);
                put("hostids",hostId);
            }});
        }};
        if(checkList!=null)
        {
          paramsMap.put("params",new HashMap<String,Object>(){{
              put("output",itemList);
              put("hostids",hostId);
              put("itemids",checkList);
          }});
        }
        // 封装数据
        Map<String, Object> responseMap = APIUtils.sendRequest(JSON.toJSONString(paramsMap, SerializerFeature.WriteMapNullValue));
        List<Map<String,Object>> itemNewsList = (List<Map<String,Object>>)responseMap.get("result");
        int total =itemNewsList.size();
        //对数据进行翻译封装
        for (int i = 0; i < itemNewsList.size(); i++) {
            TextUtils.replaceString(itemNewsList.get(i),"Zabbix","device","name");
            Map<String, Object> stringObjectMap = itemNewsList.get(i);
            String name = (String) stringObjectMap.get("name");
            stringObjectMap.put("name", initHostItem.get(name)==null?name:initHostItem.get(name));
        }
        for (int i = 0; i < itemNewsList.size(); i++) {
            DateUtils.formatListDate(itemNewsList.get(i),"lastclock");
        }
        // 此处在后端分页
        //根据curPage的值去判断是分页请求还是当前的列表展示的请求
        if (curPage != "") {
            itemNewsList = PageUtils.getDataListByCurPage(itemNewsList, curPage, pageSize);
            HashMap<String, Object> hashMap = new HashMap<>();
            hashMap.put("data_num",total);
            itemNewsList.add(hashMap);
        }
        return itemNewsList;
    }
}
